package bd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mysql.jdbc.ResultSetImpl;
import com.mysql.jdbc.Statement;

import ctrl.Ctrl;

public class MySQL {
	public static Connection conexion = null;

	public static boolean registrarDriver() {
		try {
			// ACCES:
			// Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

			// MySQL:
			Class.forName("org.gjt.mm.mysql.Driver").newInstance();

			System.out.println("Driver Registrado\n");
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static boolean abrirConexion() {
		try {
			// ACCES:
			// conexion = DriverManager.getConnection("jdbc:odbc:peliculasbd");

			// MySQL:
			conexion = DriverManager.getConnection("jdbc:mysql://"
					+ Ctrl.getServerMySQL() + ":" + Ctrl.getPortMySQL() + "/"
					+ Ctrl.getNombreBDMySQL(), Ctrl.getUsuarioMySQL(), Ctrl
					.getPasswordMySQL());

			System.out.println(conexion);
			return true;
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	public static boolean abrirConexion(String server, String port,
			String database, String user, String password) {
		try {
			// ACCES:
			// conexion = DriverManager.getConnection("jdbc:odbc:peliculasbd");

			// MySQL:
			conexion = DriverManager.getConnection("jdbc:mysql://" + server
					+ ":" + port + "/" + database, user, password);

			System.out.println(conexion);
			return true;
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	public static ArrayList<String> getCola() {

		ArrayList<String> cola = new ArrayList<String>();
		Statement instruction;
		try {

			instruction = (Statement) conexion.createStatement();

			ResultSetImpl tabla = (ResultSetImpl) instruction
					.executeQuery("SELECT q.id, s.artist, s.title FROM queuelist q, songlist s WHERE q.songid=s.id ORDER BY q.sortid;");
			while (tabla.next()) {
				cola.add(tabla.getInt(1) + ". " + tabla.getString(2) + " - "
						+ tabla.getString(3));
			}
			tabla.close();
			instruction.close();

		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}

		return cola;
	}

	public static boolean cerrarConexion() {
		try {
			conexion.close();
			// System.out.println("Conexion Cerrada\n");
			return true;
		} catch (SQLException e) {
			return false;
		}
	}

}
